package com.imooc.SmartChargeStation.netty.server.websocket;

import com.imooc.SmartChargeStation.netty.server.handlers.*;
import com.zhangyt.mqtt.protobuf.ChargingCmdProtobuf;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.timeout.IdleStateHandler;


/**
 * 自定义通道处理器
 */
public class ImmoocChannelInit  extends ChannelInitializer<SocketChannel> {

    /**
     * 通道初始化
     *
     * @param socketChannel the {@link} which was registered.
     * @throws Exception
     */
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        /* **********************
         *
         * Channel初始化是伴随ChannelPipeline的初始化
         *
         * *********************/

        //取出ChannelPipeline
        ChannelPipeline pipeline = socketChannel.pipeline();

        pipeline
                //超时检测
                .addLast(new IdleStateHandler(60,60,60))
                .addLast(new ImoocServerHeartBeatHandler())
                /**
                 * 使用Netty内置的协议编码解码器
                 * 1 HttpServerCodec
                 *   Codec作为结尾的，既可以做编码器也可以做解码器
                 *   HttpServerCodec只能解析url参数
                 */
                //对HTTP协议的GET请求解析
                .addLast(new HttpServerCodec())
                //处理http的post请求
                .addLast(new HttpObjectAggregator(65536))
                //处理http的websocket请求，自动将http协议升级成websocket协议
                .addLast(new WebSocketServerProtocolHandler("/ws"))

                //需要先把WebSocketFrame转BinaryWebSocketFrame
                //消息类型转换：将WebSocketFrame转换为BinaryWebSocketFrame
                .addLast(new ProtoMsgToMsgHandler())

                //接收数据 Protobuf的反序列化 内置处理器（需要传入二进制数据）
                .addLast(new ProtobufDecoder(ChargingCmdProtobuf.ChargingCmd.getDefaultInstance()))


                //自定义的处理器，专门处理文本类型的websocket数据
                .addLast(new ImoocWebSocketInboundHandler())
                //自定义的处理器，专门处理Protobuf解码后的数据
                .addLast(new ProtobufHandler())


                //-----------入站事件有上往下，出站事件由下往上---------------------------------

                //给小程序推送web
                .addLast(new ImoocWebSocketOutboundHandler())

        ;


    }


}


